package com.djtu.service.service.serviceImpl;

import com.djtu.exception.ServiceException;
import com.djtu.service.dao.ServiceDao;
import com.djtu.service.pojo.ServiceOrder;
import com.djtu.service.pojo.vo.RepairServiceVo;
import com.djtu.service.service.ServiceService;
import com.djtu.settings.pojo.User;
import com.djtu.settings.pojo.vo.UserVo;
import com.djtu.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.rowset.serial.SerialException;
import java.util.List;

@Service
public class ServiceServiceImpl implements ServiceService {

    @Autowired
    private ServiceDao serviceDao;

    @Override
    public void repairService(RepairServiceVo vo) throws ServiceException {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setId(StringUtil.generateUUID());
        serviceOrder.setBuildingId(vo.getBuildingId());
        serviceOrder.setAddress(vo.getAddress());
        serviceOrder.setStartTime(vo.getTime().get(0));
        serviceOrder.setEndTime(vo.getTime().get(1));
        serviceOrder.setTel(vo.getTel());
        serviceOrder.setDesc(vo.getDesc());
        // 获取当前操作用户 ID
        UserVo userVo = (UserVo) SecurityUtils.getSubject().getSession().getAttribute("userVo");
        serviceOrder.setCreater(userVo.getUserId());
        serviceOrder.setRepairer(null);
        serviceOrder.setRepairTime(null);
        serviceOrder.setStatus(1);

        int result = serviceDao.insert(serviceOrder);
        if (result != 1) {
            throw new ServiceException("报修失败");
        }
    }

    @Override
    public List<ServiceOrder> getServiceHistoryList(User user) throws ServiceException {
        Integer pageNo = Integer.valueOf(user.getTutorId());
        Integer pageSize = Integer.valueOf(user.getAdminId());
        List<ServiceOrder> serviceOrderList = serviceDao.selectListByCreaterPage(user.getId(), pageNo, pageSize);
        if (serviceOrderList == null) {
            throw new ServiceException("查询维修历史失败");
        }
        return serviceOrderList;
    }

    @Override
    public Integer getServiceHistoryListTotal(String id) {
        return serviceDao.selectTotalByCreater(id);
    }

    @Override
    public List<ServiceOrder> getAllServiceList() throws ServiceException {
        List<ServiceOrder> list = serviceDao.selectList();
        if (list == null) {
            throw new ServiceException("获取维修订单历史失败");
        }
        return list;
    }

    @Override
    public void repairServiceOk(String id) throws ServiceException {
        String repairer = ((UserVo) SecurityUtils.getSubject().getSession().getAttribute("userVo")).getUserId();
        int res = serviceDao.updateStatus2(id, repairer);
        if (res != 1) {
            throw new ServiceException("确认维修失败");
        }
    }

}
